package com.nsw99.session;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author helin
 * @email hl_0074@sina.com
 * @date 2016年8月9日
 */
public class RedisWarrpedRequest extends HttpServletRequestWrapper {

	private String sessionId;
	private RedisSession session;

	public RedisWarrpedRequest(String sessionId, HttpServletRequest request) {
		super(request);
		this.sessionId = sessionId;
	}

	@Override
	public HttpSession getSession() {

		return getSession(true);
	}

	@Override
	public HttpSession getSession(boolean create) {

		// default behavior
		HttpSession result = super.getSession(create);
		if (result == null) { return null; }

		// session JSESSIONID 相同情况下，直接返回
		if (this.session != null && result.getId().equals(this.session.getId())) { return this.session; }

		// create a redis session
		this.session = new RedisSession(sessionId, result);
		return this.session;

	}

	/**
	 * request sync session
	 *
	 * @param response
	 */
	public void afterRequest(HttpServletResponse response) {

		// 如果执行了invalidate,需要清除cookie
		if (this.session == null) { return; }
		if (!this.session.isValide()) {
			deleteClusterId(response);
		}
		this.session.sync();
	}

	/**
	 *
	 */
	private void deleteClusterId(HttpServletResponse response) {

		Cookie cookie = new Cookie(RedisSession.CLUSTER_KEY, this.sessionId);
		cookie.setPath("/");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

}
